package com.sxhuayuan.parking.dao;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import com.sxhuayuan.parking.entity.Agent;
import com.sxhuayuan.parking.entity.AgentRelation;

public interface AgentRelationDao extends BaseDao<AgentRelation, Long> {

	@Transactional
	@Modifying
	@Query(value = "delete from hypk_agent_relation where child_id = ?1", nativeQuery = true)
	void deleteRelation(Long id);

	/** 查询下级代理 */
	@Query(value = "select r.child from AgentRelation r where r.parent = ?1")
	Page<Agent> findPage(Agent parent, Pageable pageable);

	/** 查询所有下级代理 */
	@Query("select r.child from AgentRelation r where r.parent = ?1 and r.level>0")
	List<Agent> findAllChildren(Agent agent);

	@Query("select r from AgentRelation r where r.child = ?1")
	List<AgentRelation> findAllParents(Agent agent);

	@Query("select count(r.id) from AgentRelation r where r.parent = ?1 and r.child = ?2")
	Long findRelation(Agent parent, Agent child);

	/** 查询所有直接下级代理 */
	@Query("select r.child from AgentRelation r where r.parent = ?1 and r.level =1")
	List<Agent> findChildrenByParent(Agent agent);
}
